package com.panshi.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.panshi.AnswerApi;
import com.panshi.api.UserPoth;
import com.panshi.bean.UserVO;
import com.panshi.service.UserService;
import com.panshi.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class ImgController {


    @Autowired
    private UserService userService;

    @Autowired
    private AnswerApi answerApi;

    @Autowired
    private UserPoth userPoth;

    @Autowired
    private CommonUtil commonUtil;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> headImgUpload(HttpServletRequest request, MultipartFile file) throws IOException {


        Map<String, Object> value = new HashMap<String, Object>();
        value.put("success", true);
        value.put("errorCode", 0);
        value.put("errorMsg", "");
        String head = uploadImg(file);//此处是调用上传服务接口，4是需要更新的userId 测试数据。
        value.put("data", head);

        return value;
    }

    @PostMapping("/userImg")
    @ResponseBody
    public String imgUser(String upfile,HttpServletRequest request) {

        String auto_login = commonUtil.getCookie(request, "1b12ebc9bf976801fd564c64867366c5");
        System.out.println(upfile);
        if(upfile!=null){
            String userImg = userService.upload(upfile, "userImg");
            if(userImg!=null){
                System.out.println(userImg);
                UserVO userVO=new UserVO();
                userVO.setUid(Integer.valueOf(auto_login));
                userVO.setImgpath(userImg);
                userPoth.updateUser(userVO);
                return userImg;
            }else{
                return "no";
            }
        }


        return "";
    }


    @GetMapping("/test")
    public String test(){
        return "test";
    }

    public String uploadImg(MultipartFile file) throws IOException {
        /*链接阿里云*/
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI4GBFxMGpooVNmUj79Hko";
        String accessKeySecret = "eraDodgQU71xnQtSrWbC7Mv9buJOrd";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);


        InputStream inputStream = file.getInputStream();
        /*接到前台上传的文件*//*
        null;
        try {
            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //3.将上传的图片存D:\gits拼接前面的文件名
            String destFileName ="E:\\img\\" + File.separator + fileName;
            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);

            inputStream = new FileInputStream(destFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }*/



        /*上传到阿里云*/
        // 文件名格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        // 该桶中的文件key
        String dateString = "userImg/"+sdf.format(new Date()) + ".jpg";// 20180322010634.jpg
        // 上传文件
        ossClient.putObject("mysheng",dateString,inputStream);



        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL imgUrl = ossClient.generatePresignedUrl("mysheng", dateString, expiration);
        System.out.println(imgUrl.toString());

        // 关闭OSSClient。
        ossClient.shutdown();
        System.out.println("url====={}"+imgUrl.toString());
        return imgUrl.toString();
    }







}
